import React from 'react';
import { Link } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import Popover from '@iso/components/uielements/popover';

import userpic from '@iso/assets/images/user1.png';
import TopbarDropdownWrapper from './TopbarDropdown.styles';
import axios from "../../http";

import message from '@iso/components/Feedback/Message';
import MessageContent from "../Feedback/Message/Message.styles";
import Qs from 'qs'
import {createHashHistory} from "history";
import cookie from "react-cookies";



export default function TopbarUser() {
  const [visible, setVisibility] = React.useState(false);
  const dispatch = useDispatch();
  function handleVisibleChange() {
    setVisibility(visible => !visible);
  }
    function showErrorMessage (systemMessage){
        message.error(
            <MessageContent>
                {systemMessage}
            </MessageContent>,
            5
        );
    };
    function  logout(){
        axios.post('api/auth/oauth/consumer/token/revoke', Qs.stringify({
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{
                let  data=response.data;
                if(data.status==1){
                    cookie.remove('access_token');
                    let history = createHashHistory()
                    history.push({
                        pathname: "/"
                    });
                    history.go();
                }else{
                    showErrorMessage(data.message);
                }
            })
            .catch(function (error) {
                showErrorMessage(error);
            });
    }

  const content = (
    <TopbarDropdownWrapper className="isoUserDropdown">
      <Link className="isoDropdownLink" to={'/main/user/profile'}>
          个人资料
      </Link>

        <Link className="isoDropdownLink" to={'/main/user/settings'}>
            设置
        </Link>
      <div className="isoDropdownLink" onClick={logout}>
          退出
      </div>
    </TopbarDropdownWrapper>
  );

  return (
    <Popover
      content={content}
      trigger="click"
      visible={visible}
      onVisibleChange={handleVisibleChange}
      arrowPointAtCenter={true}
      placement="bottomLeft"
    >
      <div className="isoImgWrapper">
        <img alt="user" src={userpic} />
        <span className="userActivity online" />
      </div>
    </Popover>
  );
}
